package com.simple.interfaces;

import com.simple.entity.dto.SearchReturn;
import com.simple.util.JsonUtil;
import com.simple.util.LocalCache;
import com.simple.util.SpringUtil;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.web.search.WebSearchEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Objects;

/**
 * @desc
 * @Author Simple
 * @Date 2025/7/8 22:19
 **/
@Slf4j
public abstract class AbstractSearchEngineService<T> {
    protected String engineName;

    protected InetSocketAddress proxyAddress;

    protected WebSearchEngine searchEngine;

    protected T setting;

    protected AbstractSearchEngineService(String engineName, String settingName, Class<T> clazz, InetSocketAddress proxyAddress) {
        this.engineName = engineName;
        String st = LocalCache.CONFIGS.get(settingName);
        setting = JsonUtil.fromJson(st, clazz);
        this.proxyAddress = proxyAddress;
        initSearchEngine();
    }

    protected abstract void initSearchEngine();

    public abstract boolean isEnabled();

    public String getEngineName(){
        return engineName;
    }

    public abstract SearchReturn search(String searchTxt, String country, String language, Integer topN);

    protected RestTemplate getRestTemplate(){
        RestTemplate restTemplate = SpringUtil.getBean(RestTemplate.class);
        if (Objects.nonNull(proxyAddress)) {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, proxyAddress));
            restTemplate.setRequestFactory(requestFactory);
        }
        return restTemplate;
    }
}
